<template>
  <div class="login">
    <div class="panel">
      <h1>登录</h1>
      <el-form class="content" ref="LoginFormRef" :rules="rules" :model="LoginFormRef">
        <el-form-item prop="username">
          <el-input prefix-icon="el-icon-user-solid" v-model="LoginFormRef.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input prefix-icon="el-icon-lock" type="password" v-model="LoginFormRef.password"></el-input>
        </el-form-item>
        <el-form-item class="button">
          <el-button type="primary" @click="submitLoginForm">登录</el-button>
          <el-button type="info" @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { reqLogin } from '../../api'
export default {
  name: "",
  data () {
    return {
      LoginFormRef: {
        username: "admin",
        password: "123456",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 18, message: "长度在 6 到 18 个字符", trigger: "blur" },
        ],
      },
    }
  },
  methods: {
    // 提交表单的同一验证
    submitLoginForm () {
      this.$refs.LoginFormRef.validate(async (valid) => {
        // 校验非空
        if (!valid) return false
        // 获取表单数据
        const { username, password } = this.LoginFormRef
        // 发送请求
        const result = await reqLogin(username, password)
        // console.log(result)
        // 校验返回的响应结果
        if (result.code === 20000) {
          // 清除以前的信息，避免二次登陆
          this.$store.dispatch('resetInfo')

          // 提示登录成功
          this.$message.success(result.data.message)
          // 保存后台的token
          this.$store.dispatch('saveInfo', result.data)

          // 动态添加路由
          this.$store.commit('addMenu', this.$router)
          // 跳转到管理页面
          this.$router.replace("/")
        } else {
          return this.$message.error(result.data.message)
        }
      })
    },
    // 重置登录表单
    resetForm (formName) {
      console.log("resetForm", this)
      this.$refs.LoginFormRef.resetFields()
    },
  },
}
</script>
<style lang="less" scoped>
.login {
  position: relative;
  width: 100%;
  height: 100%;
  background-color: rgb(46, 199, 201);

  .panel {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 450px;
    height: 380px;
    background-color: #fff;
    border-radius: 10px;

    h1 {
      text-align: center;
      margin-top: 20px;
      font-size: 30px;
    }

    .el-form {
      padding: 50px 20px;
    }

    /deep/.el-form-item__content {
      text-align: right;
    }
  }
}
</style>
